<template>
  <div class="announcement-container">
    <h2>站点公告</h2>
    
    <!-- 公告列表 -->
    <el-card class="announcement-list">
      <el-table
        :data="announcements"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="title" label="公告标题" min-width="300"></el-table-column>
        <el-table-column prop="publishedAt" label="发布时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.publishedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="showDetail(scope.row)"
            >详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 公告详情对话框 -->
    <el-dialog
      title="公告详情"
      :visible.sync="detailVisible"
      width="50%"
    >
      <div class="announcement-detail">
        <h3>{{ currentAnnouncement.title }}</h3>
        <div class="meta-info">
          <span>发布人：{{ currentAnnouncement.publisher }}</span>
          <span>发布时间：{{ formatDate(currentAnnouncement.publishedAt) }}</span>
        </div>
        <div class="content">{{ currentAnnouncement.content }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AnnouncementNotification',
  data() {
    return {
      announcements: [],
      ws: null,
      detailVisible: false,
      currentAnnouncement: {}
    }
  },
  mounted() {
    this.fetchAnnouncements()
    this.initWebSocket()
  },
  methods: {
    // 获取所有公告
    async fetchAnnouncements() {
      try {
        const res = await this.$http.get('/platform/announcement/selectAnnouncement')
        if (res.data.code === 200) {
          this.announcements = res.data.data
        }
      } catch (error) {
        console.error('获取公告失败：', error)
      }
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      if (typeof date === 'object') {
        // 处理WebSocket返回的日期对象
        const { year, monthValue, dayOfMonth, hour, minute } = date
        return `${year}-${String(monthValue).padStart(2, '0')}-${String(dayOfMonth).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
      }
      return date.replace('T', ' ').substring(0, 16)
    },

    // 显示公告详情
    showDetail(announcement) {
      this.currentAnnouncement = announcement
      this.detailVisible = true
    },

    // 初始化WebSocket
    initWebSocket() {
      // 添加重连机制
      const connectWebSocket = () => {
        // this.ws = new WebSocket("ws://192.168.50.8:9081/websocket")
        this.ws = new WebSocket("ws://localhost:9081/websocket")

        this.ws.onopen = () => {
          console.log('WebSocket连接成功')
        }
      // this.ws = new WebSocket("ws://localhost:9081/websocket")

        this.ws.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data)
            this.$notify({
              title: '新公告',
              message: `${data.title}\n发布时间：${this.formatDate(data.publishedAt)}`,
              type: 'success',
              duration: 5000,
              position: 'top-right'
            })
            this.fetchAnnouncements()
          } catch (error) {
            console.error('WebSocket消息处理错误:', error)
          }
        }

        this.ws.onerror = (error) => {
          console.error('WebSocket错误:', error)
          setTimeout(connectWebSocket, 5000)  // 5秒后重试
        }

        this.ws.onclose = () => {
          console.log('WebSocket连接关闭')
          setTimeout(connectWebSocket, 5000)  // 5秒后重试
        }
      }

      connectWebSocket()
    }
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close()
    }
  }
}
</script>

<style scoped>
.announcement-container {
  padding: 20px;
}

.announcement-list {
  margin-top: 20px;
}

.announcement-detail {
  padding: 20px;
}

.announcement-detail h3 {
  margin: 0 0 20px 0;
  text-align: center;
  font-size: 20px;
  color: #303133;
}

.meta-info {
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.content {
  line-height: 1.8;
  font-size: 14px;
  color: #606266;
  white-space: pre-wrap;
}

h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}
</style>
